package top.hmtools.configurations;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
public class MybatisConfiguration {
    
    private static final String SQLSESSION_BEAN_NAME="sqlSessionFactoryBean"; 
    
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(SqlSessionFactory sqlSessionFactory,ApplicationContext applicationContext){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setApplicationContext(applicationContext);
        configurer.setBasePackage("top.hmtools.daos.**");
        configurer.setSqlSessionFactoryBeanName(SQLSESSION_BEAN_NAME);
        return configurer;
    }

    /**
     * 获取mybatis session  工厂
    * 方法说明：                    sqlSessionFactoryBean
    * 输入参数说明：           @param dataSource
    * 输入参数说明：           @return
    * 输入参数说明：           @throws Exception
    * 输出参数说明：           SqlSessionFactory
    *
    *
     */
    @Bean(SQLSESSION_BEAN_NAME)
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource)
            throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mappers/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
    
    /**
     * 获取SqlSessionTemplate
     * 
     * @return
     */
  @Bean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
      return new SqlSessionTemplate(sqlSessionFactory);
  }
}
